<?php

namespace App\Http\Controllers\group;

use App\Models\Commission;
use App\Models\GroupMember;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class NextController extends BaseController
{
    public function preview()
    {
        $userId = auth('jwt')->id();
        $total = GroupMember::query()
            ->where('leader_id', $userId)
            ->whereHas('member', function ($query) {
                $query->where('is_group_leader', 1);
            })
            ->count();

        $yesterday = GroupMember::query()
            ->where('leader_id', $userId)
            ->whereHas('member', function ($query) {
                $query->where('is_group_leader', 1);
            })
            ->whereDate('updated_at', Carbon::yesterday())
            ->count();

        $today = GroupMember::query()
            ->where('leader_id', $userId)
            ->whereHas('member', function ($query) {
                $query->where('is_group_leader', 1);
            })
            ->whereDate('updated_at', Carbon::today())
            ->count();

        return $this->success([
            'total' => $total,
            'today' => $today,
            'yesterday' => $yesterday,
        ]);
    }

    public function detail(Request $request)
    {
        $userId = auth('jwt')->id();
        $members = GroupMember::query()
            ->with('member:id,uuid,nickname')
            ->where('leader_id', $userId)
            ->whereHas('member', function ($query) {
                $query->where('is_group_leader', 1);
            })
            ->get();

        $list = [];
        foreach ($members as &$member) {
            $user = $member->member;
            $yesterday = Commission::query()
                ->where('user_id', $user->id)
                ->whereDate('child_user_withdraw_at', Carbon::yesterday())
                ->sum('user_money');
            $today = Commission::query()
                ->where('user_id', $user->id)
                ->whereDate('child_user_withdraw_at', Carbon::today())
                ->sum('user_money');
            $list[] = [
                'id' => $member->member->id,
                'uuid' => $member->member->uuid,
                'nickname' => $member->member->nickname,
                'yesterday_income' => $yesterday,
                'today_income' => $today,
            ];
        }

        return $this->success($list);
    }
}
